﻿using MediaInfoDotNet;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Expressing_Label
{
    public partial class VideoForm : Form
    {
       
        private bool m_FormMove = false;            //窗体鼠标拖动标记
        private bool m_TextFocus = false;           //同步输入框获取焦点标记
        private bool m_Capturing = false;           //截图状态标记
        private Point m_CurrentPoint = new Point(); //窗体移动初始坐标记录
        private double m_SyncTime = 0;              //同步时间
        private Size m_CaptureSize = new Size();    //截屏尺寸
        private Size m_SelectedSize = new Size();   //框选尺寸
        private Size m_TmpSelectedSize = new Size();
        private Point m_TmpDrawRecPoint = new Point();
        private double m_CurrentPosition = 0;
        private bool m_isPlaying = false;
        private Bitmap m_FormCaptureBmp;            //截屏缓存位图
        private Bitmap m_FormCaptureBmpDbl;         //截屏缓存位图_第二缓存
        private Bitmap m_FormCaptureBmpMin;         //框选之后的脸部位图
        private bool m_isCapturePictureFront = false;
        private bool m_DrawRec = false;             //矩形框绘制标记
        private Point m_DrawRecPoint = new Point(); //矩形框左上角顶点
        private bool m_DrawRecDone = false;         //矩形绘制完成标记
        private Point m_PlayerToForm = new Point();
        private double m_VideoProportion = 0;
        private double m_ZoomProportion = 0;
        private bool m_BarDragging = false;
        private int m_BarDragValue = 0;
        private string[] m_TmpFileLocation = new string[2];
        private string m_TmpExpressing = "";
        private string m_CurrentExpressing = "";
        private string m_strCurrentPosition = "";
        private double m_TmpCurrentPosition = 0;
        private string m_strTmpCurrentPosition = "";
        private Bitmap m_bmpTmpImage = null;
        private Bitmap m_bmpTmpImagemin = null;
        private static Queue<tb_ExpressingInfo> tbQueue = new Queue<tb_ExpressingInfo>();
        private bool m_IsCaptureDeleted = true;
        private bool m_isSavingToSQL = false;
        private Thread m_threadSaveToSQL = null;
        private int m_CurrentIndex = 0;
        private int m_TmpIndex = 0;
        private Thread m_threadCaptureByCmd = null;
        private bool m_blCaptureFinished = true;
        private ToolTip m_tipPlayerBar = new ToolTip();
        public static InformationMiForm c_frmInfo;
        public bool m_isFrmClosing = false;
        private int m_iCloseState = 0;
        private string c_strPromptShow = "";
        private bool c_isFasterPlaying = false;
        private string c_strPlayerTime = "";
        public static bool g_isUserInfoDone = false;
        private bool c_isVideoAdding = false;
        public static int c_xInfoPicbx = 0;
        private int m_iVideoWidth = 1920;
        private int m_iVideoHeight = 1080;
        private bool m_isSavingToTmp = false;
        

        

        //窗体构造函数，实例化，变量初始化
        public VideoForm()
        {
            InitializeComponent();
            InitializeControlsLocation();
            InitializeExpressing();
            InitializePlayerBar();
            InitializePlayerControl();
            InitializeGroupBox();
        }

        private void InitializeControlsLocation()
        {
            //Initialize the BaseGroupBox
            this.BaseGroup.Location = new System.Drawing.Point(0, 45);
            this.BaseGroup.Size = new System.Drawing.Size(1200, 614);
            BaseGroup.Visible = false;

            //Initialize the BaseLabel
            lblBase.Left = (Width - lblBase.Width) / 2;
            lblBase.Top = (Height - lblBase.Height) / 2;

            //Initialize the CapturePlayer
            this.CapturePlayer.Location = new System.Drawing.Point(10, 20);
            this.CapturePlayer.Size = new System.Drawing.Size(800, 460);
            m_PlayerToForm.X = CapturePlayer.Location.X + BaseGroup.Location.X;
            m_PlayerToForm.Y = CapturePlayer.Location.Y + BaseGroup.Location.Y;

            //Initialize the VideoPlayer
            this.VideoPlayer.Enabled = true;
            this.VideoPlayer.Location = new System.Drawing.Point(828, 20);
            this.VideoPlayer.Size = new System.Drawing.Size(187, 168);

            //Initialize the PlayerGroupBox
            this.PlayerGroup.Location = new System.Drawing.Point(10, 500);
            this.PlayerGroup.Size = new System.Drawing.Size(675, 100);

            //Initialize the ReviewGroupBox
            this.ReviewGroup.Location = new System.Drawing.Point(720, 500);
            this.ReviewGroup.Size = new System.Drawing.Size(466, 100);

            //Initialize the CountInfoGroupBox
            this.CountInfoGroup.Location = new System.Drawing.Point(1034, 20);
            this.CountInfoGroup.Size = new System.Drawing.Size(154, 168);

            //Initialize the ExpressingGroupBox
            this.ExpressionGroup.Location = new System.Drawing.Point(828, 196);
            this.ExpressionGroup.Size = new System.Drawing.Size(360, 280);

            //Initialize the Sync
            m_SyncTime = 0;
            SyncText.ForeColor = Color.Gray;
            SyncText.Text = "0";

            c_xInfoPicbx = Info_picbx.Left;
        }

        private void InitializeExpressing()
        {
            for (int i = 0; i < PublicResources.g_ExpressingSourceItem.Count; i += 5)
            {
                int j = i / 5;
                foreach (Control c in ExpressionGroup.Controls)
                {
                    if (c is GroupBox && c.TabIndex == j + 7)                                               //Set GroupName
                    {
                        (c as GroupBox).Text = PublicResources.g_ExpressingSourceItem[i];
                        foreach (Control r in c.Controls)
                        {
                            if (r is RadioButton)
                            {
                                (r as RadioButton).Enabled = false;
                                (r as RadioButton).Visible = false;
                            }
                        }
                        int t = 0;
                        for (int k = 1; k < 5; k++)
                        {
                            string s = PublicResources.g_ExpressingSourceItem[j * 5 + k];
                            s = s.Substring(0, s.LastIndexOf('#'));
                            if (!s.EndsWith("0"))
                            {
                                foreach (Control r in c.Controls)
                                    if (r is RadioButton && (r as RadioButton).TabIndex == t)
                                    {
                                        t++;
                                        RadioButton tr = (RadioButton)r;
                                        tr.Visible = true;
                                        tr.Enabled = true;
                                        tr.Text = s;
                                        tr.CheckedChanged += new System.EventHandler(this.Radio_CheckedChanged);
                                        break;
                                    }
                            }
                        }
                    }
                }
            }
        }

        private void InitializePlayerBar()
        {
            PlayerBar.Location = new Point(CapturePlayer.Location.X, CapturePlayer.Location.Y + CapturePlayer.Height + 10);
            PlayerBar.Size = new Size(CapturePlayer.Width, 8);
            PlayerTrackButton.Location = new Point(PlayerBar.Left, PlayerBar.Top - 5);
            m_tipPlayerBar.UseFading = true;
            m_tipPlayerBar.UseAnimation = true;
            m_tipPlayerBar.AutoPopDelay = 2000;
            m_tipPlayerBar.ReshowDelay = 1000;
        }

        private void InitializePlayerControl()
        {
            SetButtonStyle(PlayerGroup.Controls);
        }

        private void SetButtonStyle(Control.ControlCollection cc)
        {
            foreach (Control c in cc)
            {
                if (c is Button)
                {
                    Button b = (c as Button);
                    b.FlatStyle = FlatStyle.Flat;
                    b.FlatAppearance.BorderSize = 0;
                    b.FlatAppearance.MouseDownBackColor = Color.PaleTurquoise;
                    b.FlatAppearance.MouseOverBackColor = Color.LightCyan;
                    b.MouseHover += new EventHandler(PlayButton_MouseHover);
                    b.MouseEnter += new EventHandler(PlayButton_MouseEnter);
                    b.MouseLeave += new EventHandler(PlayButton_MouseLeave);
                }
            }
        }


        private void InitializeGroupBox()
        {
            IterationInitialize(this.Controls);
        }

        private void IterationInitialize(Control.ControlCollection ic)
        {
            foreach (Control c in ic)
            {
                if (c is GroupBox)
                {
                    (c as GroupBox).Paint += new PaintEventHandler(BaseGroup_Paint);
                }
                if (c.Controls.Count > 0)
                    IterationInitialize(c.Controls);
            }
        }

       
        


        //退出程序
        private void ExitPicture_Click(object sender, EventArgs e)
        {
            c_strPromptShow = "正在保存数据，请稍候";
            m_iCloseState = 0;
            FormExit_Mtd();
        }


        private void FormExit_Mtd()
        {
            m_isFrmClosing = true;
            ThreadPrompt_Mtd();
            timClosing.Start();
            timSelfBackup.Stop();
            SaveToTemp_Mtd(true);
            if (!m_IsCaptureDeleted)
                TbCache_Mtd();
            m_IsCaptureDeleted = true;
            btnAbandon.Enabled = false;
            btnAbandon.BackColor = Color.Gray;
            if (tbQueue.Count != 0 || m_threadSaveToSQL == null || !m_threadSaveToSQL.IsAlive)
            {
                m_threadSaveToSQL = new Thread(SaveCaptureToSQL_Mtd);
                m_threadSaveToSQL.IsBackground = true;
                m_threadSaveToSQL.Start();
                
            }   
        }

        //窗体配置，启动
        private void VideoForm_Load(object sender, EventArgs e)
        {
            CapturePlayer.enableContextMenu = false;
            VideoPlayer.enableContextMenu = false;
            VideoPlayer.settings.volume = 0;
            btnAbandon.Enabled = false;
            btnAbandon.BackColor = Color.Gray;
            m_blCaptureFinished = true;
            m_IsCaptureDeleted = true;
            g_isUserInfoDone = false;
            c_isVideoAdding = false;
            lbCaptureCount.Text = "截图" + PublicResources.g_CaptureTimes.ToString() + "次";
            lbSaveCount.Text = "存储" + PublicResources.g_ExpresingCaptureRecord[12, 0].ToString() + "张";

            if (PublicResources.g_iConfiguraState < 5)
            {
                Info_picbx.BackColor = Color.DimGray;
                picAnalysis.BackColor = Color.DimGray;
            }
            else if(PublicResources.g_iConfiguraState == 6)
            {
                PromptFrm pf = new PromptFrm("检测到未正常退出程序，将恢复程序状态，请稍候");
                pf.Show();
                Info_picbx.BackColor = Color.Transparent;
                picAnalysis.BackColor = Color.Transparent;
                BaseGroup.Visible = true;
                AddVideo_Mtd();
            }
        }

        //鼠标拖动窗口down，move，up，leave
        private void VideoForm_MouseDown(object sender, MouseEventArgs e)
        {
            m_FormMove = true;
            m_CurrentPoint = MousePosition;
        }

        private void VideoForm_MouseMove(object sender, MouseEventArgs e)
        {
            if (m_FormMove)
            {
                int x = MousePosition.X - m_CurrentPoint.X;
                int y = MousePosition.Y - m_CurrentPoint.Y;
                this.Left += x;
                this.Top += y;
                m_CurrentPoint = MousePosition;
            }
        }

        private void VideoForm_MouseUp(object sender, MouseEventArgs e)
        {
            m_FormMove = false;
        }

        private void VideoForm_MouseLeave(object sender, EventArgs e)
        {
            m_FormMove = false;
        }

        //播放按钮事件，调用播放方法
        private void PlayButton_Click(object sender, EventArgs e)
        {
            PlayerPlayPause_Mtd();
        }


        //停止按钮事件
        private void StopButton_Click(object sender, EventArgs e)
        {
            PlayerStop_Mtd();

        }

        //同步按钮事件，调用同步检测方法
        private void SyncButton_Click(object sender, EventArgs e)
        {
            SyncCheck_Method();
        }

        //同步检测方法，输入合法检测，播放媒体就位检测
        private void SyncCheck_Method()
        {
            bool ok = true;
            int len = SyncText.Text.Length;
            if (len == 0)
            {
                ok = false;
            }
            else
            {
                for (int i = 0; i < len; i++)
                {
                    if (!char.IsNumber(SyncText.Text[i]))
                    {
                        ok = false;
                        break;
                    }
                }
            }
            if (ok)
            {
                VideoPlayer.Focus();
                PromptLabel.Visible = false;
                m_SyncTime = Convert.ToDouble(SyncText.Text);
                if (btnSymbol.Text == "-")
                    m_SyncTime = -m_SyncTime;
                if (CapturePlayer.URL != "")            //输入合法，播放媒体就位，调用同步方法
                    Sync_Method();
            }
            else
            {
                PromptLabel.Visible = true;
                SyncText.Clear();
                SyncText.Focus();
            }
        }

        //同步方法，以CapturePlayer播放进度为参考，调整VideoPlayer播放进度
        private void Sync_Method()
        {
            double sy = m_SyncTime;
            double cpt = CapturePlayer.Ctlcontrols.currentPosition;
            double tmp = cpt + sy;
            if (tmp < 0 && CapturePlayer.URL != "")
            {
                VideoPlayer.Ctlcontrols.stop();
                int t = Convert.ToInt32(-tmp * 1000);
                SyncTimer.Interval = t;
                SyncTimer.Start();
            }
            else
            {
                VideoPlayer.Ctlcontrols.currentPosition = tmp;
                PlayerPlay_Method();
            }
        }

        //同步数据输入框，默认值全选，获取焦点，键盘Enter检测
        private void SyncText_Enter(object sender, EventArgs e)
        {
            SyncText.ForeColor = Color.Black;
            SyncText.SelectAll();
            m_TextFocus = true;
        }

        //同步数据输入框，防止MouseUp事件失去全选
        private void SyncText_MouseUp(object sender, MouseEventArgs e)
        {
            if (m_TextFocus)
            {
                SyncText.SelectAll();
            }
            m_TextFocus = false;
        }

        //开始截图方法，修改开始截图标记，获取CapturePlayer位置，尺寸，用于从屏幕截取，缓存到FormCaptureBmp并显示
        private void CaptureBegin_Method()
        {
            if (!m_Capturing)
            {
                CaptureButton.Enabled = false;
                CaptureButton.BackColor = Color.Gray;
                m_Capturing = true;
                m_DrawRec = false;
                m_DrawRecDone = false;
                m_CaptureSize = CapturePlayer.Size;
                m_FormCaptureBmp = new Bitmap(m_CaptureSize.Width, m_CaptureSize.Height);
                m_FormCaptureBmpDbl = new Bitmap(m_CaptureSize.Width, m_CaptureSize.Height);
                PlayerPause_Method();
                m_CurrentPosition = CapturePlayer.Ctlcontrols.currentPosition;
                Graphics gra = Graphics.FromImage(m_FormCaptureBmp);
                gra.Clear(Color.White);
                gra.CopyFromScreen(PointToScreen(m_PlayerToForm), new Point(0, 0), CapturePlayer.Size);
                CapturePicture.Image = m_FormCaptureBmp;
                CapturePicture.Location = CapturePlayer.Location;
                CapturePicture.BringToFront();
                m_isCapturePictureFront = true;
                CapturePicture.Refresh();
                CapturePicture.Focus();
                gra.Dispose();
            }
        }

        //捕获视频按钮事件，调用开始截图方法
        private void CaptureButton_Click(object sender, EventArgs e)
        {
            CaptureBegin_Method();
        }

        //鼠标按下开始对捕获视频进行矩形选取，判断活动窗口，正在捕获，矩形选取未完成
        private void CapturePicture_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && m_isCapturePictureFront && !m_DrawRecDone && m_Capturing && !m_DrawRec)
            {
                m_DrawRec = true;
                m_TmpDrawRecPoint.X = e.X;
                m_TmpDrawRecPoint.Y = e.Y;
            }
        }

        //鼠标拖动对捕获视频的矩形选取，判断是否开始进行矩形选取，在二级缓存位图绘制矩形框并显示
        private void CapturePicture_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && m_DrawRec)
            {
                m_TmpSelectedSize.Width = e.X - m_TmpDrawRecPoint.X;
                m_TmpSelectedSize.Height = e.Y - m_TmpDrawRecPoint.Y;
                Pen p = new Pen(Color.White, 2);
                Graphics gra = Graphics.FromImage(m_FormCaptureBmpDbl);
                gra.DrawImage(m_FormCaptureBmp, new Point(0, 0));
                gra.DrawRectangle(p, m_TmpDrawRecPoint.X, m_TmpDrawRecPoint.Y, m_TmpSelectedSize.Width, m_TmpSelectedSize.Height);
                CapturePicture.Image = m_FormCaptureBmpDbl;
                CapturePicture.Refresh();
                gra.Dispose();
            }
        }

        //鼠标释放，判断是否矩形选取完成，关闭正在绘制矩形
        private void CapturePicture_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && m_DrawRec && !m_DrawRecDone && m_Capturing && m_TmpSelectedSize.Width > 10 && m_TmpSelectedSize.Height > 10)
            {
                m_DrawRecDone = true;
                m_DrawRecPoint = m_TmpDrawRecPoint;
                m_TmpDrawRecPoint.X = e.X;
                m_TmpDrawRecPoint.Y = e.Y;
                m_SelectedSize = m_TmpSelectedSize;
                m_TmpSelectedSize = new Size(0, 0);
            }
            m_DrawRec = false;
        }

        //鼠标离开，关闭正在绘制矩形
        private void CapturePicture_MouseLeave(object sender, EventArgs e)
        {
            m_DrawRec = false;

        }

        //绘制完成按钮，调用绘制完成方法
        private void DoneButton_Click(object sender, EventArgs e)
        {
            CaptureDone_Method();
        }

        //绘制完成方法，判断矩形绘制完成，判断单选表情
        private void CaptureDone_Method()
        {
            bool p_RadioButtonChecked = false;
            RadioButton r = new RadioButton();
            foreach (Control c in ExpressionGroup.Controls)
            {
                if (c is GroupBox)
                {
                    foreach (Control cc in (c as GroupBox).Controls)
                    {
                        if (cc is RadioButton && (cc as RadioButton).Checked)
                        {
                            p_RadioButtonChecked = true;
                            r = (cc as RadioButton);
                            break;
                        }
                    }
                }
                if(p_RadioButtonChecked)
                    break;
            }

            //单选表情，矩形绘制完成，关闭正在捕获，关闭矩形绘制，关闭矩形绘制完成，关闭表情单选，保存截图,放弃按钮置为不可用
            
            if (p_RadioButtonChecked && m_DrawRecDone)
            {
                //Resume Player, record CaptureTimes
                PlayerPlay_Method();
                PublicResources.g_CaptureTimes++;
                lbCaptureCount.Text = "截图" + PublicResources.g_CaptureTimes.ToString() + "次";
                //变量重置与保存
                InitDrawVariable_Mtd();
                
                r.Checked = false;

                //ForTest_Mtd();
                //判断之前保存是否完成，若未完成，放弃此次操作
                if (!m_blCaptureFinished)
                    MessageBox.Show("Hold on!");
                else
                {
                    m_blCaptureFinished = false;
                    btnAbandon.Enabled = false;
                    btnAbandon.BackColor = Color.Gray;

                    //Save Cuurent information to Tmp information
                    SaveCurrentToTmp(r);
                    
                    //判断保存信息到数据库
                   
                    if (!m_IsCaptureDeleted)
                    {                        
                        TbCache_Mtd();
                        if (m_threadSaveToSQL == null || (tbQueue.Count >= 10 && !m_threadSaveToSQL.IsAlive))
                        {
                            SaveToTemp_Mtd(false);
                            m_threadSaveToSQL = new Thread(SaveCaptureToSQL_Mtd);
                            m_threadSaveToSQL.IsBackground = true;
                            m_threadSaveToSQL.Start();
                        }
                    }

                    //Refresh TempSavingViarable,生成图片名字，年月日+性格编号+院系编号+视频时间点+1+三位随机数
                    MakeFileName_Mtd();

                    //调用cmd后台运行ffmpeg.exe进行截图，对截图进行裁剪
                    //根据所画矩形获得人脸并保存
                    //更新截图回顾信息
                    m_threadCaptureByCmd = new Thread(CaptureByCmd_Mtd);
                    m_threadCaptureByCmd.IsBackground = true;
                    m_threadCaptureByCmd.Start();

                    
                }

            }
            else if (!p_RadioButtonChecked)
            {
                if (MessageBox.Show("请选择表情") == DialogResult.OK)
                    CapturePicture.Focus();
            }
            else
            {
                if (MessageBox.Show("请选择脸部") == DialogResult.OK)
                    CapturePicture.Focus();
            }
        }

        private void SaveCurrentToTmp(RadioButton r)
        {
            m_CurrentExpressing = r.Text;
            m_CurrentIndex = r.Parent.TabIndex - 6;
            int minute = (int)(m_CurrentPosition / 60);
            int second = (int)(m_CurrentPosition % 60);
            m_strCurrentPosition = "";
            if (minute != 0)
                m_strCurrentPosition += minute.ToString() + "分";
            m_strCurrentPosition += second.ToString() + "秒";
        }


        private void TbCache_Mtd()
        {
            int x = (int)(m_TmpCurrentPosition / 180);
            int y = PublicResources.g_ExpressingSelectedIndex[m_TmpExpressing] + 5;
            int z = m_TmpIndex;
            int m = (int)m_TmpCurrentPosition;
            if (x > 9)
                x = 9;

            tb_ExpressingInfo tb = new tb_ExpressingInfo();
            for (int i = 0; i < PublicResources.g_VideoModelDetail.Count; i++)
            {
                int t = PublicResources.g_VideoModelDetail[i].IndexOf("#");
                int tt = Convert.ToInt32(PublicResources.g_VideoModelDetail[i].Substring(t + 1));
                if (m <= tt)
                {
                    tb.CurrentVideoContent = PublicResources.g_VideoModelDetail[i].Substring(0, t);
                    break;
                }
            }
            
            tb.UserID = PublicResources.g_iUserID;
            //tb.VideoTimeFloat = (float)m_TmpCurrentPosition;
            //tb.Rectangle = m_recTmpDrawDes.X.ToString() + "," + m_recTmpDrawDes.Y.ToString() + "," + m_recTmpDrawDes.Width.ToString() + "," + m_recTmpDrawDes.Height.ToString();
            tb.ImageLocation = PublicResources.g_strImageLocation;
            tb.Weather = PublicResources.g_strWeather;
            tb.Location = PublicResources.g_strLocation;
            tb.Expressing_Self = m_TmpExpressing;
            tb.CurrentVideoTime = m_strTmpCurrentPosition;
            tb.ExperimentDuration = PublicResources.g_ExperimentDuration;
            tb.ExperimentStartTime = PublicResources.g_dtStartTime;
            tb.OtherTimes = 0;
            tb.Expressing_OtherDetail = "0,0,0,0,0,0,0,0,0,0";
            tb.MaxEpressing = "0";
            tb.MaxTimes = 0;
            tbQueue.Enqueue(tb);
            tb.ExperimentID = PublicResources.g_iExperimentID;

            //Save for Analysis

            PublicResources.g_ExpresingCaptureRecord[x, 0]++;
            PublicResources.g_ExpresingCaptureRecord[x, y]++;
            PublicResources.g_ExpresingCaptureRecord[x, z]++;
            PublicResources.g_ExpresingCaptureRecord[12, 0]++;
            PublicResources.g_ExpresingCaptureRecord[12, y]++;
            PublicResources.g_ExpresingCaptureRecord[12, z]++;
            lbSaveCount.Text = "存储" + PublicResources.g_ExpresingCaptureRecord[12, 0].ToString() + "张";
        }


        private void SaveCaptureToSQL_Mtd()
        {
            m_isSavingToSQL = true;
            //Save to SQL
            using (db_FACEEntities db = new db_FACEEntities())
            {                
                while (tbQueue.Count > 0)
                {
                    db.tb_ExpressingInfo.Add(tbQueue.Dequeue());
                    if (m_isFrmClosing)
                    {
                        tb_UserInfo tb = new tb_UserInfo();
                        tb.UserID = PublicResources.g_iUserID;
                        tb.Gender = PublicResources.g_blUserGender;
                        tb.Department = PublicResources.g_strUserDepartment;
                        tb.Character = PublicResources.g_strUserCharacter;
                        tb.SelfDiscribing = PublicResources.g_strSelfDiscribing;
                        tb.PHysicalCondition = PublicResources.g_strPhysicalCondition;
                        tb.SumOfExpressing = PublicResources.g_ExpresingCaptureRecord[12, 0];
                        tb.SumOfDetail = PublicResources.g_ExpresingCaptureRecord[12, 1].ToString() + "," + PublicResources.g_ExpresingCaptureRecord[12, 2].ToString() + "," + PublicResources.g_ExpresingCaptureRecord[12, 3].ToString() + "," + PublicResources.g_ExpresingCaptureRecord[12, 4].ToString();
                        tb.VideoEffectivity = PublicResources.g_strVideoEffectivity;
                        tb.CharacterQuery = PublicResources.g_strCharacter; ;
                        tb.FeelingShowing = PublicResources.g_strFeeling;
                        tb.CharecterResult = PublicResources.g_strCharacterResult;
                        tb.FeelingResult = PublicResources.g_strFeelingResult;
                        tb.ExperimentID = PublicResources.g_iExperimentID;
                        var result = from info in db.tb_UserInfo
                                     where info.UserID == PublicResources.g_iUserID
                                     select new
                                     {
                                         id = info.ID
                                     };
                        if (result.Count() == 0)
                            db.tb_UserInfo.Add(tb);
                        else
                        {
                            var re = result.ToArray();
                            tb.ID = re[0].id;
                            db.tb_UserInfo.Attach(tb);
                            db.Entry(tb).State = System.Data.Entity.EntityState.Modified;
                        }
                        db.SaveChanges();
                        m_isFrmClosing = false;
                    }
                }
                db.SaveChanges();
            }
            m_isSavingToSQL = false;
        }

        private void InitDrawVariable_Mtd()
        {
            m_DrawRec = false;
            m_DrawRecDone = false;
            m_Capturing = false;
        }

        private void MakeFileName_Mtd()
        {
            if (m_CurrentPosition - m_TmpCurrentPosition < 10)
                PublicResources.g_CaptureInTenSec++;
            m_TmpCurrentPosition = m_CurrentPosition;
            m_TmpExpressing = m_CurrentExpressing;
            m_TmpIndex = m_CurrentIndex;
            m_strTmpCurrentPosition = m_strCurrentPosition;

            Random ran = new Random();
            int t = ran.Next(1, 999);
            t += 1000;

            PublicResources.g_strImageLocation = PublicResources.g_strImageBaseName + ((int)(m_TmpCurrentPosition * 100)).ToString() + t.ToString();
            m_TmpFileLocation[0] = PublicResources.g_strImageLocation + ".png";
            m_TmpFileLocation[1] = PublicResources.g_strImageLocation + "_min.png";
        }



        private void CaptureByCmd_Mtd()
        {
            Process ffmpeg = new Process();
            string strMediaWidth = m_iVideoWidth.ToString();
            string strMediaHeight = m_iVideoHeight.ToString();
            ffmpeg.StartInfo.Arguments = "-ss " + m_TmpCurrentPosition + " -i \"" + CapturePlayer.URL + "\" -vframes 1 " + "-s " + strMediaWidth + "x" + strMediaHeight + " " + m_TmpFileLocation[0];
            ffmpeg.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            ffmpeg.StartInfo.FileName = @"ffmpeg.exe";
            ffmpeg.Start();
            ffmpeg.WaitForExit();
            ffmpeg.Close();
            ffmpeg.Dispose();

            Bitmap bmpMin = new Bitmap(m_SelectedSize.Width, m_SelectedSize.Height);
            Graphics graMin = Graphics.FromImage(bmpMin);
            Rectangle desMin = new Rectangle(0, 0, m_SelectedSize.Width, m_SelectedSize.Height);
            Rectangle resMin = new Rectangle(m_DrawRecPoint.X, m_DrawRecPoint.Y, m_SelectedSize.Width, m_SelectedSize.Height);
            graMin.DrawImage(m_FormCaptureBmp, desMin, resMin, GraphicsUnit.Pixel);
            m_bmpTmpImage = (Bitmap)m_FormCaptureBmp.Clone();
            m_bmpTmpImagemin = (Bitmap)bmpMin.Clone();
            //bmpMin.Save(PublicResources.g_strImageLocation + "_minTest.png", ImageFormat.Png);

            //GetFaceWithRectangle
            m_DrawRecPoint.X -= CapturePlayer.DisplayRectangle.Left;
            m_DrawRecPoint.Y -= CapturePlayer.DisplayRectangle.Top;
            double x1 = m_DrawRecPoint.X * 1.0 / CapturePlayer.DisplayRectangle.Width;
            double y1 = m_DrawRecPoint.Y * 1.0 / CapturePlayer.DisplayRectangle.Height;
            double x2 = m_SelectedSize.Width * 1.0 / CapturePlayer.DisplayRectangle.Width;
            double y2 = m_SelectedSize.Height * 1.0 / CapturePlayer.DisplayRectangle.Height;

            FileStream fs = new FileStream(@m_TmpFileLocation[0], FileMode.Open);
            Bitmap b = (Bitmap)Bitmap.FromStream(fs);
            fs.Close();

            m_DrawRecPoint.X = (int)(b.Width * x1);
            m_DrawRecPoint.Y = (int)(b.Height * y1);
            m_SelectedSize.Width = (int)(b.Width * x2);
            m_SelectedSize.Height = (int)(b.Height * y2);
            //m_SelectedSize.Width = (int)(m_SelectedSize.Width * m_ZoomProportion);
            //m_SelectedSize.Height = (int)(m_SelectedSize.Height * m_ZoomProportion);

            //m_DrawRecPoint.X = (int)(m_DrawRecPoint.X * m_ZoomProportion);
            //m_DrawRecPoint.Y = (int)(m_DrawRecPoint.Y * m_ZoomProportion);
            m_FormCaptureBmpMin = new Bitmap(m_SelectedSize.Width, m_SelectedSize.Height);
            Rectangle des = new Rectangle(0, 0, m_SelectedSize.Width, m_SelectedSize.Height);
            Rectangle res = new Rectangle(m_DrawRecPoint.X, m_DrawRecPoint.Y, m_SelectedSize.Width, m_SelectedSize.Height);


            
            Graphics gra = Graphics.FromImage(m_FormCaptureBmpMin);
            gra.DrawImage(b, des, res, GraphicsUnit.Pixel);
            m_FormCaptureBmpMin.Save(@m_TmpFileLocation[1], ImageFormat.Png);
            //m_bmpTmpImage = (Bitmap)b.Clone();
            //m_bmpTmpImagemin = (Bitmap)m_FormCaptureBmpMin.Clone();

            b.Dispose();
            gra.Dispose();
            m_FormCaptureBmpMin.Dispose();
            //Refresh Review Information            
            
            MethodInvoker mi = new MethodInvoker(this.RefreshReviewControls_Mtd);
            this.BeginInvoke(mi);
        }

        private void RefreshReviewControls_Mtd()
        {
            lblLastCaptureInfo.Text = m_strTmpCurrentPosition + "-" + m_TmpExpressing;
            picbxBigCapture.Image = m_bmpTmpImage;
            picbxMinCapture.Image = m_bmpTmpImagemin;
            btnAbandon.Enabled = true;
            btnAbandon.BackColor = Color.Transparent;
            m_blCaptureFinished = true;
            m_IsCaptureDeleted = false;
        }

        //播放器播放方法，关闭矩形绘制，关闭矩形绘制完成，关闭正在捕获
        private void PlayerPlay_Method()
        {
            CaptureButton.Enabled = true;
            CaptureButton.BackColor = Color.Transparent;
            m_isPlaying = true;
            PlayButton.Tag = "暂停";
            m_DrawRec = false;
            m_DrawRecDone = false;
            m_Capturing = false;
            CapturePlayer.BringToFront();
            m_isCapturePictureFront = false;
            PlayerBarTimer.Start();
            PlayButton.BackgroundImage = Properties.Resources.pause;
            try
            {
                CapturePlayer.Ctlcontrols.play();
                VideoPlayer.Ctlcontrols.play();
            }
            catch (Exception ex)
            {
                if (MessageBox.Show("视频播放异常，请联系王琳大人") == DialogResult.OK)
                {
                    this.Owner.Show();
                    this.Close();
                }
            }
        }

        private void PlayerPlayPause_Mtd()
        {
            if (m_isPlaying)
                PlayerPause_Method();
            else
                PlayerPlay_Method();
        }

        //CaputrePlayer播放状态改变判断，正在播放，同步
        private void CapturePlayer_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {
            if (CapturePlayer.playState == WMPLib.WMPPlayState.wmppsPlaying && !m_Capturing)
            {
                if (CapturePlayer.Ctlcontrols.currentPosition + m_SyncTime != VideoPlayer.Ctlcontrols.currentPosition)
                {
                    Sync_Method();
                }
            }
            else if(CapturePlayer.playState == WMPLib.WMPPlayState.wmppsMediaEnded)
            {
                m_isPlaying = false;
                PlayButton.BackgroundImage = Properties.Resources.play;
                PlayerBarTimer.Stop();
                PlayerBar.Value = 0;
                TrackButtonLocationMethod();
                PlayButton.Tag = "播放";
            }
        }

        //同步计时器
        private void SyncTimer_Tick(object sender, EventArgs e)
        {
            PlayerPlay_Method();
            SyncTimer.Stop();
        }

        //同步输入框键盘Enter事件
        private void SyncText_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
                SyncCheck_Method();
        }

        //视频捕获双击鼠标左键事件，调用完成截图方法
        private void CapturePicture_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                CaptureDone_Method();
            }
        }

        //视频捕获单击鼠标右键事件，取消矩形框，关闭矩形绘制，关闭矩形框绘制完成
        private void CapturePicture_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (m_DrawRecDone)
                {
                    m_DrawRec = false;
                    m_DrawRecDone = false;
                    CapturePicture.Image = m_FormCaptureBmp;
                    CapturePicture.Refresh();
                }
                else
                    PlayerPlay_Method();
            }
        }

        //窗体键盘事件
        private void VideoForm_KeyDown(object sender, KeyEventArgs e)
        {
            Keys k = e.KeyCode;
            if (k == Keys.Escape || k == Keys.P)
                PlayerPlay_Method();
            else if (k == Keys.S && !m_Capturing)
            {
                PlayerStop_Mtd();
            }
            else if (k == Keys.C)
                CaptureBegin_Method();
            else if (k == Keys.A && !m_Capturing)
            {
                PlayerPause_Method();
            }
            else if (k == Keys.Enter && m_Capturing)
                CaptureDone_Method();
        }

        private void PlayerPause_Method()
        {
            m_isPlaying = false;
            PlayButton.Tag = "播放";
            PlayButton.BackgroundImage = Properties.Resources.play;
            CapturePlayer.Ctlcontrols.pause();
            PlayerBarTimer.Stop();
            VideoPlayer.Ctlcontrols.pause();
        }

        private void PlayerStop_Mtd()
        {
            m_isPlaying = false;
            PlayButton.BackgroundImage = Properties.Resources.play;
            CapturePlayer.Ctlcontrols.stop();
            VideoPlayer.Ctlcontrols.stop();
            PlayerBarTimer.Stop();
            PlayerBar.Value = 0;
            TrackButtonLocationMethod();
            PlayButton.Tag = "播放";
        }

        private void CapturePlayer_MediaChange(object sender, AxWMPLib._WMPOCXEvents_MediaChangeEvent e)
        {
            if (CapturePlayer.currentMedia.duration == 0)
                MessageBox.Show("视频已损坏，请联系王琳大人");
            else
            {
                if(CapturePlayer.currentMedia.sourceURL.EndsWith(".m2ts"))
                {
                    //m_iVideoWidth = 1920;
                    //m_iVideoHeight = 1080;
                    CapturePlayer.stretchToFit = true;

                }
                else
                {
                    m_iVideoWidth = CapturePlayer.currentMedia.imageSourceWidth;
                    m_iVideoHeight = CapturePlayer.currentMedia.imageSourceHeight;
                }
                TimeSpan ts = new TimeSpan(0, 0, (int)CapturePlayer.currentMedia.duration);
                c_strPlayerTime = ts.ToString();
                lblCurrentTime.Text = "00:00:00/" + c_strPlayerTime;
                m_VideoProportion = m_iVideoWidth * 1.0 / m_iVideoHeight;
                CapturePlayer.Height = (int)(CapturePlayer.DisplayRectangle.Width / m_VideoProportion);
                m_ZoomProportion = m_iVideoWidth * 1.0 / CapturePlayer.DisplayRectangle.Width;
                CapturePicture.Size = CapturePlayer.DisplayRectangle.Size;
                CapturePicture.Location = CapturePlayer.Location;
                PlayerBar.Location = new Point(CapturePlayer.Location.X, CapturePlayer.Location.Y + CapturePlayer.Height + 10);
                PlayerBar.Maximum = (int)CapturePlayer.currentMedia.duration;
                PlayerBar.Value = (int)CapturePlayer.Ctlcontrols.currentPosition;
                TrackButtonLocationMethod();
            }
        }


        private void PlayerBarTimer_Tick(object sender, EventArgs e)
        {
            if (!m_Capturing)
            {
                PlayerBar.Value = (int)CapturePlayer.Ctlcontrols.currentPosition;
                TimeSpan ts = new TimeSpan(0, 0, PlayerBar.Value);
                lblCurrentTime.Text = ts.ToString() + "/" + c_strPlayerTime;
                TrackButtonLocationMethod();
            }
        }

        private void TrackButtonLocationMethod()
        {
            int xPosition = (int)(PlayerBar.Value * 1.0 / PlayerBar.Maximum * PlayerBar.Size.Width) + PlayerBar.Location.X;
            PlayerTrackButton.Location = new Point(xPosition - 5, PlayerBar.Location.Y - 5);
        }

        private void BarClickMethod(int x, int v)
        {
            int xPosition = x - PlayerBar.Location.X;
            if (xPosition > 0)
            {
                int xValue = (int)(xPosition * 1.0 / PlayerBar.Width * PlayerBar.Maximum);
                if (v != xValue)
                {
                    CapturePlayer.Ctlcontrols.currentPosition = (double)xValue;
                    PlayerBar.Value = xValue;
                    TrackButtonLocationMethod();
                    Sync_Method();
                }
            }
        }

        private void PlayerBar_Click(object sender, EventArgs e)
        {
            if (!m_BarDragging)
                BarClickMethod(PointToClient(MousePosition).X, PlayerBar.Value);
        }

        private void PlayerTrackButton_MouseDown(object sender, MouseEventArgs e)
        {
            m_BarDragging = true;
            m_BarDragValue = PlayerBar.Value;
        }

        private void PlayerTrackButton_MouseMove(object sender, MouseEventArgs e)
        {
            if (m_BarDragging)
            {
                PlayerTrackButton.Location = new Point(PointToClient(MousePosition).X, PlayerBar.Location.Y - 5);
                this.Refresh();
            }
        }

        private void PlayerTrackButton_MouseUp(object sender, MouseEventArgs e)
        {
            if (m_BarDragging)
                BarClickMethod(PointToClient(MousePosition).X, m_BarDragValue);
            m_BarDragging = false;
        }

        private void PlayerTrackButton_MouseLeave(object sender, EventArgs e)
        {
            m_BarDragging = false;
        }

        private void BackButton_Click(object sender, EventArgs e)
        {
            if (!m_Capturing)
            {
                if (c_isFasterPlaying)
                {
                    c_isFasterPlaying = false;
                    CapturePlayer.settings.rate = 1.0;
                    Sync_Method();
                }
                else
                {
                    c_isFasterPlaying = true;
                    CapturePlayer.settings.rate = -2.0;
                }
            }
        }


        private void ForwardButton_Click(object sender, EventArgs e)
        {
            if (!m_Capturing)
            {
                if (!c_isFasterPlaying)
                {
                    c_isFasterPlaying = true;
                    CapturePlayer.settings.rate = 2.0;
                }
                else
                {
                    c_isFasterPlaying = false;
                    CapturePlayer.settings.rate = 1.0;
                    Sync_Method();
                }
            }
        }

        private void LastButton_Click(object sender, EventArgs e)
        {
            if (m_Capturing && CapturePlayer.Ctlcontrols.currentPosition > 1.0)
            {
                CapturePlayer.BringToFront();
                CapturePlayer.Ctlcontrols.currentPosition -= 0.11;
                PlayerPlay_Method();
                PlayerPause_Method();
                CapturePlayer.Ctlcontrols.pause();
                Application.DoEvents();
                CaptureBegin_Method();
            }
        }

        private void NextButton_Click(object sender, EventArgs e)
        {
            if (m_Capturing&& CapturePlayer.Ctlcontrols.currentPosition < CapturePlayer.currentMedia.duration - 1.0)
            {
                CapturePlayer.BringToFront();
                CapturePlayer.Ctlcontrols.currentPosition += 0.1;
                PlayerPlay_Method();
                PlayerPause_Method();
                Application.DoEvents();
                CaptureBegin_Method();
            }
        }


        private void Info_picbx_Click(object sender, EventArgs e)
        {
            if (PublicResources.g_iConfiguraState >= 5)
                if (c_frmInfo == null || c_frmInfo.IsDisposed)
                {
                    c_frmInfo = new InformationMiForm();
                    c_frmInfo.Owner = this;
                    c_frmInfo.Show();
                    g_isUserInfoDone = false;
                }
        }

        private void VideoForm_Activated(object sender, EventArgs e)
        {
            foreach (var item in this.OwnedForms)
                item.Close();
            if (g_isUserInfoDone)
            {
                Info_picbx.BackColor = Color.Transparent;
                picAnalysis.BackColor = Color.Transparent;
                BaseGroup.Visible = true;
                if (!c_isVideoAdding)
                {
                    AddVideo_Mtd();
                    SaveToTemp_Mtd(false);
                }
            }
        }

        //打开视频所在文件夹，依据视频源调整播放器宽、高
        private void AddVideo_Mtd()
        {
            c_isVideoAdding = true;
            bool ok = true;
            string[] videoList = Directory.GetFiles(@"Video");
            if (videoList.Count() < 2)
                ok = false;
            for (int i = 0; i < videoList.Count(); i++)
            {
                if (videoList[i].Contains("capture."))
                {
                    using (MediaFile mf = new MediaFile(videoList[i]))
                    {
                        m_iVideoWidth = mf.Video[0].width;
                        m_iVideoHeight = mf.Video[0].height;
                    }
                    CapturePlayer.URL = videoList[i];
                }
                if (videoList[i].Contains("video."))
                    VideoPlayer.URL = videoList[i];
            }
            if (CapturePlayer.URL == "" || VideoPlayer.URL == "")
                ok = false;

            if (ok)
            {
                if(PublicResources.g_iConfiguraState == 6)
                {
                    CapturePlayer.Ctlcontrols.play();
                    CapturePlayer.Ctlcontrols.currentPosition = PublicResources.g_dCurrentPosition;
                    Sync_Method();
                    timSelfBackup.Start();
                    PublicResources.g_iConfiguraState = 5;
                }
                else if (MessageBox.Show("视频加载成功，点击确定开始截图", "确认") == DialogResult.OK)
                {
                    SyncCheck_Method();
                    timSelfBackup.Start();
                }
            }
            else
            {
                if (MessageBox.Show("视频加载失败，请联系王琳大人") == DialogResult.OK)
                {
                    m_iCloseState = 3;
                    FormExit_Mtd();
                }
            }

        }

        private void btnSymbol_Click(object sender, EventArgs e)
        {
            if (btnSymbol.Text == "+")
                btnSymbol.Text = "-";
            else
                btnSymbol.Text = "+";
        }

        //多个groupbox中多个radiobutton单选处理
        private void Radio_CheckedChanged(object sender, EventArgs e)
        {
            if (sender is RadioButton)
            {
                if (((RadioButton)sender).Checked)
                {
                    GroupBox gb = ((RadioButton)sender).Parent as GroupBox;
                    foreach (Control c in ExpressionGroup.Controls)
                    {
                        if (c is GroupBox && !c.Equals(gb))
                        {
                            foreach (Control cc in c.Controls)
                            {
                                if (cc is RadioButton)
                                    (cc as RadioButton).Checked = false;
                            }
                        }
                    }
                }
            }
        }


        private void picBackToWelcome_Click(object sender, EventArgs e)
        {
            c_strPromptShow = "正在保存数据，请稍候";
            m_iCloseState = 3;
            FormExit_Mtd();
        }

        

        private void ForTest_Mtd()
        {
            Bitmap testbmp = new Bitmap(m_SelectedSize.Width, m_SelectedSize.Height);
            Graphics testgra = Graphics.FromImage(testbmp);
            Rectangle testdes = new Rectangle(0, 0, m_SelectedSize.Width, m_SelectedSize.Height);
            Rectangle testres = new Rectangle(m_DrawRecPoint.X, m_DrawRecPoint.Y, m_SelectedSize.Width, m_SelectedSize.Height);
            testgra.DrawImage(m_FormCaptureBmp, testdes, testres, GraphicsUnit.Pixel);
            testbmp.Save(@PublicResources.g_strImageBaseName + "_test.png");
            testgra.Dispose();
        }

        private void btnAbandon_Click(object sender, EventArgs e)
        {
            picbxBigCapture.Image = null;
            picbxMinCapture.Image = null;
            for (int i = 0; i < 2; i++)
            {
                if (File.Exists(m_TmpFileLocation[i]))
                    File.Delete(m_TmpFileLocation[i]);
            }
            lblLastCaptureInfo.Text = "暂无数据";
            m_IsCaptureDeleted = true;
            btnAbandon.Enabled = false;
            btnAbandon.BackColor = Color.Gray;
        }

        private void picAnalysis_Click(object sender, EventArgs e)
        {
            if (PublicResources.g_iConfiguraState >= 5)
            {
                m_iCloseState = 1;
                FormExit_Mtd();
            }
        }

        private string CurrentPositionToTime(double pos)
        {
            int min = (int)(pos / 60);
            int sec = (int)(pos % 60);
            string s = "";
            if (min < 10)
                s = "0";
            s += min.ToString() + ":";
            if (sec < 10)
                s += "0";
            s += sec.ToString();
            return s;
        }

        private void PlayerTrackButton_MouseHover(object sender, EventArgs e)
        {
            if (CapturePlayer.URL != "")
            {
                m_tipPlayerBar.Show(CurrentPositionToTime(CapturePlayer.Ctlcontrols.currentPosition), PlayerTrackButton);               
            }
        }

        private void PlayerBar_MouseHover(object sender, EventArgs e)
        {
            if (CapturePlayer.URL != "")
            {
                int x = PointToClient(MousePosition).X;
                double currentpos = (x - PlayerBar.Left) * 1.0 / PlayerBar.Width * PlayerBar.Maximum;
                m_tipPlayerBar.Show(CurrentPositionToTime(currentpos), PlayerBar);
            }
        }

        private void picbxLabelByOther_Click(object sender, EventArgs e)
        {
            c_strPromptShow = "连接中，请稍候";
            m_iCloseState = 2;
            FormExit_Mtd();
            
        }

        private void timClosing_Tick(object sender, EventArgs e)
        {

            if (!m_isSavingToSQL && m_blCaptureFinished)
            {
                if (m_threadSaveToSQL != null)
                    m_threadSaveToSQL.Abort();
                if (m_threadCaptureByCmd != null)
                    m_threadCaptureByCmd.Abort();
                if (m_iCloseState == 0)
                    System.Environment.Exit(0);
                else if (m_iCloseState == 1)
                {
                    InfoAnalysisFrm iaf = new InfoAnalysisFrm();
                    PlayerPlay_Method();
                    PlayerPause_Method();
                    iaf.Owner = this;
                    this.Hide();
                    iaf.Show();
                }
                else if (m_iCloseState == 2)
                {
                    LableByOtherFrm lbof = new LableByOtherFrm();
                    lbof.Owner = this;
                    lbof.Show();
                    this.Hide();
                }
                else
                {
                    this.Owner.Show();
                    this.Close();
                }
                timClosing.Stop();
            }

        }

        private void CapturePlayer_ClickEvent(object sender, AxWMPLib._WMPOCXEvents_ClickEvent e)
        {
            CaptureBegin_Method();
        }

        private void ThreadPrompt_Mtd()
        {
            PromptFrm pf = new PromptFrm(c_strPromptShow);
            pf.Show();
        }

        private void PlayButton_MouseHover(object sender, EventArgs e)
        {
            if (sender is Button)
            {
                Button b = (Button)sender;
                m_tipPlayerBar.Show(b.Tag.ToString(), b);
            }
        }

        private void BaseGroup_Paint(object sender, PaintEventArgs e)
        {
            Pen p = new Pen(Color.BlueViolet);
            p.DashStyle = DashStyle.Custom;
            p.DashPattern = new Single[] { 3, 2, 2, 1 };
            GroupBox gb = (GroupBox)sender;
            Graphics gra = e.Graphics;
            gra.Clear(gb.BackColor);
            gra.DrawString(gb.Text, gb.Font, Brushes.Blue, 10, 1);
            gra.DrawLine(p, 1, 7, 8, 7);
            gra.DrawLine(p, gra.MeasureString(gb.Text, gb.Font).Width + 8, 7, gb.Width - 2, 7);
            gra.DrawLine(p, 1, 7, 1, gb.Height - 2);
            gra.DrawLine(p, 1, gb.Height - 2, gb.Width - 2, gb.Height - 2);
            gra.DrawLine(p, gb.Width - 2, 7, gb.Width - 2, gb.Height - 2);
        }

        private void PlayButton_MouseEnter(object sender, EventArgs e)
        {
            Button b = (Button)sender;
            b.Top -= 1;
            b.Left -= 1;
        }

        private void PlayButton_MouseLeave(object sender, EventArgs e)
        {
            Button b = (Button)sender;
            b.Top += 1;
            b.Left += 1;
        }

        private void timSelfBackup_Tick(object sender, EventArgs e)
        {
            SaveToTemp_Mtd(false);
        }

        private void SaveToTemp_Mtd(bool ok)
        {
            if (!m_isSavingToTmp)
            {
                m_isSavingToTmp = true;
                if (File.Exists(@"Data\r.tmp"))
                    File.Delete(@"Data\r.tmp");
                FileStream fs = new FileStream(@"Data\r.tmp", FileMode.Create);
                StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                sw.WriteLine(ok);

                sw.WriteLine(PublicResources.g_iConfiguraState);
                sw.WriteLine(PublicResources.g_iUserNum);
                sw.WriteLine(PublicResources.g_iUserID);
                sw.WriteLine(PublicResources.g_dtStartTime.ToString());
                sw.WriteLine(PublicResources.g_strWeather);
                sw.WriteLine(PublicResources.g_strLocation);
                sw.WriteLine(PublicResources.g_blUserGender.ToString());
                sw.WriteLine(PublicResources.g_strUserCharacter);
                sw.WriteLine(PublicResources.g_strUserDepartment);
                sw.WriteLine(PublicResources.g_strPhysicalCondition);
                sw.WriteLine(PublicResources.g_strSelfDiscribing);
                sw.WriteLine(PublicResources.g_strImageBaseName);
                sw.WriteLine(CapturePlayer.Ctlcontrols.currentPosition.ToString());
                sw.WriteLine(PublicResources.g_CaptureTimes);
                sw.WriteLine(PublicResources.g_iExperimentID);
                sw.WriteLine(PublicResources.g_ExpressingSourceItem.Count);
                for (int i = 0; i < PublicResources.g_ExpressingSourceItem.Count; i++)
                {
                    sw.WriteLine(PublicResources.g_ExpressingSourceItem[i]);
                }
                sw.WriteLine(PublicResources.g_VideoModelDetail.Count);
                for (int i = 0; i < PublicResources.g_VideoModelDetail.Count; i++)
                {
                    sw.WriteLine(PublicResources.g_VideoModelDetail[i]);
                }
                for (int i = 0; i < 15; i++)
                {
                    string s = "";
                    for (int j = 0; j < 25; j++)
                    {
                        s += PublicResources.g_ExpresingCaptureRecord[i, j].ToString() + " ";
                    }
                    sw.WriteLine(s);
                }

                sw.Close();
                fs.Close();
                m_isSavingToTmp = false;
            }
            
        }

        //private void PlayButton_Paint(object sender, PaintEventArgs e)
        //{
        //    Bitmap bmpBob = (Bitmap)Properties.Resources.play;
        //    GraphicsPath graphicsPath = CalculateControlGraphicsPath(bmpBob);
        //    this.PlayButton.Region = new Region(graphicsPath);  
        //}

        //private static GraphicsPath CalculateControlGraphicsPath(Bitmap bitmap)
        //{

        //    GraphicsPath graphicsPath = new GraphicsPath();


        //    Color colorTransparent = bitmap.GetPixel(0, 0);

        //    int colOpaquePixel = 0;

        //    for (int row = 0; row < bitmap.Height; row++)
        //    {

        //        colOpaquePixel = 0;

        //        for (int col = 0; col < bitmap.Width; col++)
        //        {

        //            if (bitmap.GetPixel(col, row) != colorTransparent)
        //            {

        //                colOpaquePixel = col;

        //                int colNext = col;

        //                for (colNext = colOpaquePixel; colNext < bitmap.Width; colNext++)
        //                    if (bitmap.GetPixel(colNext, row) == colorTransparent)
        //                        break;

        //                graphicsPath.AddRectangle(new Rectangle(colOpaquePixel,
        //                 row, colNext - colOpaquePixel, 1));

        //                col = colNext;
        //            }
        //        }
        //    }

        //    return graphicsPath;
        //}

    }
}
